<template>
  <div class="app-container">
    <!-- 功能按钮栏 -->
    <div class="filter-container">
      <!-- <el-input
        v-model="listQuery.search"
        placeholder="权限名"
        style="width: 200px;"
        class="filter-item"
        @change="handleFilter"
      /> -->
      <el-date-picker
        v-model="listQuery.range"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
        @change="handleFilter"
      />
      &nbsp;
      &nbsp;
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>

      <!-- <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        新增
      </el-button> -->
    </div>
    <!-- 数据列表 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      stripe
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column prop="uploadspeed" label="上传量" min-width="150" />
      <el-table-column prop="downloadspeed" label="下载量" min-width="150" />
      <el-table-column prop="device" label="设备ID" min-width="150" />

      <el-table-column label="时间" width="160px" align="center">
        <template slot-scope="scope">
          <span>{{
            scope.row.timestamp | parseTime("{y}-{m}-{d} {h}:{i}")
          }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作区"
        fixed="right"
        align="center"
        width="180"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button
            size="mini"
            type="danger"
            style="width: auto;"
            icon="el-icon-delete"
            @click="handleDelete(row._id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.currentPage"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <!-- 添加和修改界面 -->

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="90px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="权限名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>

        <el-form-item label="权限" prop="access" />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import flows from "@/api/flows";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import pagesizeMixin from "@/mixins/pagesize";
import baseMixin from "@/mixins/base";

export default {
  name: "Flows",
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        true: "success",
        false: "danger"
      };
      return statusMap[status];
    }
  },
  mixins: [baseMixin, pagesizeMixin],
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      title: "流量",
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        // 查询关键字
        isPaging: true,
        currentPage: 1,
        pageSize: 20,
        search: undefined,
        range: ""
      },
      showReviewer: false,
      // 表单提交的数据
      temp: {
        id: undefined,
        name: "",
        access: ""
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "修改",
        create: "新增"
      },
      // 验证方法
      rules: {
        name: [{ required: true, message: "名称必须填写", trigger: "blur" }],
        access: [{ required: true, message: "权限必须填写", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      flows.list(this.listQuery).then(response => {
        this.list = response.data.data && response.data.data.list;
        this.total = response.data.data ? response.data.data.count : 0;

        this.listLoading = false;
      });
    },
    handleFilter() {
      this.listQuery.currentPage = 1;
      // console.log(this.listQuery.range);
      this.listQuery.start = this.listQuery.range[0];
      this.listQuery.end = this.listQuery.range[1];
      this.getList();
    },

    resetTemp() {
      this.temp = {
        id: undefined,
        name: "",
        access: ""
      };
    },
    // 弹起添加界面
    handleCreate() {
      flows.newly().then(response => {
        this.resetTemp();
      });
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    // 添加方法
    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          flows.create(this.temp).then(res => {
            if (this.errorInfo(res)) return;
            this.list.unshift(res.data.data);
            this.dialogFormVisible = false;
            this.successInfo();
          });
        }
      });
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj

      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp);

          flows.update(tempData._id, tempData).then(res => {
            if (this.errorInfo(res)) return;
            for (const v of this.list) {
              if (v._id === tempData._id) {
                this.list.splice(this.list.indexOf(v), 1, tempData);
                break;
              }
            }
            this.dialogFormVisible = false;
            this.successInfo();
          });
        }
      });
    },
    handleDelete(id) {
      this.$confirm("是否删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        flows.remove(id).then(res => {
          if (this.errorInfo(res)) return;
          for (const v of this.list) {
            if (v._id === id) {
              this.list.splice(this.list.indexOf(v), 1);
              break;
            }
          }
          this.dialogFormVisible = false;
          this.successInfo();
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped></style>
